package com.chaosj.tools

import com.chaosj.tools.rules.CombinationRule
import com.google.common.base.Joiner
import com.google.common.base.Splitter

import java.nio.file.Files
import java.nio.file.StandardOpenOption
import java.time.LocalDate
import java.util.stream.Stream

class StockDiscoverTools {
    static List<String> descLists = Arrays.asList(
            "股票名称#name","今日开盘价#openingPrice","昨日开盘价#yesClosePrice","当前价格#currPrice","今日最高价#todayMaxPrice",
            "今日最低价#todayMinPrice","竞价买1#bidBuyPrice","竞价卖1#bidSellPrice","成交股数#dealCount","成交金额#dealPrice",
            "买1数#buy1","买1金额#buy1Price","买2数#buy2","买2金额#buy2Price","买3数#buy3","买3金额#buy3Price","买4数#buy4","买4金额#buy4Price","买5数#buy5","买5金额#buy5Price",
            "卖1数#sell1","卖1金额#sell1Price","卖2数#sell2","卖2金额#sell2Price","卖3数#sell3","卖3金额#sell3Price","卖4数#sell4","卖4金额#sell4Price","卖5数#sell5","卖5金额#sell5Price","日期#date"
    );

    static void requestStockInfo(List<String> stocks,String storePath){
        String requestURI = Joiner.on(",").join(stocks.stream().map({v->v.startsWith("60")?"sh"+v:"sz"+v}).collect())
        String value = HttpClientUtils.sendGetRequest("http://hq.sinajs.cn/list="+requestURI)
        List<String> values = Splitter.on("\n").splitToList(value)
        values.parallelStream().filter({x->x!=""&&x!=null}).forEach({stock->
            try{
                List<String> stockInfo = Splitter.on(",").splitToList(stock.split("\\=")[1])
                DescriptionStock ds = new DescriptionStock()
                for( int i = 0; i < descLists.size(); i++){
                    String descStr = descLists.get(i)
                    ds.putAt(descStr.split("\\#")[1],stockInfo.get(i))
                }
                String fileName = ds.name.replace("\"","").replace(" ","")
                new File(storePath+"\\"+fileName+".store").createNewFile()
                isExecuteToday(storePath,fileName,LocalDate.now().toString()+"#"+JsonTools.toJson(ds))
            }catch(Exception e){
                println(stock+e.getMessage())
            }
        })
        println("拉取最新数据完成")
    }

    private static boolean isExecuteToday(String storePath,String fileName,String json){
        List<String> lines = Files.readAllLines(new File(storePath+"\\"+fileName+".store").toPath())
        String date = LocalDate.now().toString()
        boolean haved = lines.stream().filter({line->line.startsWith(date)}).findAny().isPresent()
        lines.add(json)
        if( haved ){
            Files.delete(new File(storePath+"\\"+fileName+".store").toPath())
            lines.removeAt(lines.size()-2)
            Files.write(new File(storePath+"\\"+fileName+".store").toPath(),lines,StandardOpenOption.CREATE_NEW)
            return haved
        }
        Files.write(new File(storePath+"\\"+fileName+".store").toPath(),lines,StandardOpenOption.WRITE)
        return haved
    }

    static String analysisStocks(List<String> stores,String storeBasePath){
        stores.stream().forEach({stock->
            Collection<StockDiscoverTools.DescriptionStock> datas = Files.readAllLines(new File(storeBasePath+"\\"+stock+".store").toPath()).stream().flatMap({line->
                StockDiscoverTools.DescriptionStock stockInfo = JsonTools.parseObject(Splitter.on("#").splitToList(line)[1],StockDiscoverTools.DescriptionStock.class)
                Stream.of(stockInfo)
            }).collect()
            CombinationRule.getInstance().execute(stock,datas)
        })
    }

    static enum ResultEnum{
        // 上涨
        UP,
        // 下跌
        DOWN,
        // 大涨后回调
        LIMIT_DOWN,
        // 不变
        EQUAL,
        ;
    }

    static class DescriptionStock{
        //股票名称
        String name
        //开盘价格
        String openingPrice
        //昨天收盘价
        String yesClosePrice
        //当前价格
        String currPrice
        //今天最高价
        String todayMaxPrice
        //今天最低价
        String todayMinPrice
        //竞价买1
        String bidBuyPrice
        //竞价卖1
        String bidSellPrice
        //成交股数
        String dealCount
        //成交金额
        String dealPrice
        //买一数
        String buy1
        //买一价
        String buy1Price
        //买一数
        String buy2
        //买一价
        String buy2Price
        //买一数
        String buy3
        //买一价
        String buy3Price
        //买一数
        String buy4
        //买一价
        String buy4Price
        //买一数
        String buy5
        //买一价
        String buy5Price
        //卖一数
        String sell1
        //卖一价
        String sell1Price
        //卖一数
        String sell2
        //卖一价
        String sell2Price
        //卖一数
        String sell3
        //卖一价
        String sell3Price
        //卖一数
        String sell4
        //卖一价
        String sell4Price
        //卖一数
        String sell5
        //卖一价
        String sell5Price
        //日期
        String date

        ResultEnum upDownFlag(){
            if( Float.valueOf(currPrice)-Float.valueOf(yesClosePrice) < 0 ){
                // 下跌
                return ResultEnum.DOWN
            }else if( Float.valueOf(currPrice)-Float.valueOf(yesClosePrice) > 0 ) {
                // 上涨
                return ResultEnum.UP
            }else if( Float.valueOf(todayMaxPrice)/Float.valueOf(currPrice) > 1.05 ){
                // 大涨后下跌
                return ResultEnum.LIMIT_DOWN
            }else{
                return ResultEnum.EQUAL
            }
        }

        /**
         * 昨天暴涨9个点以上并且尾盘回调
         * @return
         */
        boolean fallBack(){
            if( (Float.valueOf(todayMaxPrice)/Float.valueOf(openingPrice)) >= 1.09 && (Float.valueOf(currPrice)/Float.valueOf(todayMaxPrice)) <=0.97 ){
                return true
            }
            return false
        }

        boolean span(Double value){
            if( Float.valueOf(todayMaxPrice)/Float.valueOf(todayMinPrice) >= value){
                return true
            }
            return false
        }

        boolean dailyLimit(){
            if( currPrice == todayMaxPrice && Float.valueOf(currPrice)/Float.valueOf(yesClosePrice)>1.09 ){
               return true
            }
            return false
        }

        Float todayUp(){
            return Float.valueOf(currPrice)/Float.valueOf(yesClosePrice)
        }

        @Override
        String toString() {
            return "DescriptionStock{" +
                    "name='" + name + '\'' +
                    ", openingPrice=" + openingPrice +
                    ", yesClosePrice=" + yesClosePrice +
                    ", currPrice=" + currPrice +
                    ", todayMaxPrice=" + todayMaxPrice +
                    ", todayMinPrice=" + todayMinPrice +
                    ", bidBuyPrice=" + bidBuyPrice +
                    ", bidSellPrice=" + bidSellPrice +
                    ", dealCount=" + dealCount +
                    ", dealMoney=" + dealPrice +
                    ", buy1=" + buy1 +
                    ", buy1Price=" + buy1Price +
                    ", buy2=" + buy2 +
                    ", buy2Price=" + buy2Price +
                    ", buy3=" + buy3 +
                    ", buy3Price=" + buy3Price +
                    ", buy4=" + buy4 +
                    ", buy4Price=" + buy4Price +
                    ", buy5=" + buy5 +
                    ", buy5Price=" + buy5Price +
                    ", sell1=" + sell1 +
                    ", sell1Price=" + sell1Price +
                    ", sell2=" + sell2 +
                    ", sell2Price=" + sell2Price +
                    ", sell3=" + sell3 +
                    ", sell3Price=" + sell3Price +
                    ", sell4=" + sell4 +
                    ", sell4Price=" + sell4Price +
                    ", sell5=" + sell5 +
                    ", sell5Price=" + sell5Price +
                    ", date='" + date + '\'' +
                    '}'
        }
    }
}
